import { NextRequest, NextResponse } from 'next/server';
import { authMiddleware, TokenPayload } from '@/utils/auth';
import UserModel from '@/models/user';

export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      return authResult; // 返回错误响应
    }

    const decoded = authResult as TokenPayload;
    const userId = decoded.id;

    // 获取用户信息
    const user = await UserModel.findById(userId);
    if (!user) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 404 }
      );
    }

    // 检查用户是否为企业负责人
    if (!user.is_company_admin) {
      return NextResponse.json(
        { error: '您不是企业负责人，无法更新招聘状态' },
        { status: 403 }
      );
    }

    const jobId = params.id;
    if (!jobId || isNaN(Number(jobId))) {
      return NextResponse.json(
        { error: '无效的职位ID' },
        { status: 400 }
      );
    }

    // 解析请求体
    const body = await request.json();
    const { status } = body;

    if (!status || !['active', 'inactive'].includes(status)) {
      return NextResponse.json(
        { error: '无效的状态值' },
        { status: 400 }
      );
    }

    // 检查职位是否存在且属于该用户的企业
    const [jobs] = await UserModel.query<any[]>(
      `SELECT jp.*, c.admin_user_id 
       FROM job_positions jp
       LEFT JOIN companies c ON jp.company_id = c.id
       WHERE jp.id = ?`,
      [jobId]
    );

    if (!jobs || jobs.length === 0) {
      return NextResponse.json(
        { error: '职位不存在' },
        { status: 404 }
      );
    }

    const job = jobs[0];
    
    // 检查职位是否属于该用户的企业
    if (job.admin_user_id !== userId) {
      return NextResponse.json(
        { error: '您无权更新此招聘信息' },
        { status: 403 }
      );
    }

    // 更新职位状态
    await UserModel.query(
      `UPDATE job_positions SET status = ?, updated_at = NOW() WHERE id = ?`,
      [status, jobId]
    );

    return NextResponse.json({
      message: `招聘状态已更新为${status === 'active' ? '已发布' : '已下线'}`,
      job_id: jobId,
      status
    });
  } catch (error) {
    console.error('更新招聘状态错误:', error);
    return NextResponse.json(
      { error: '服务器错误，请稍后再试' },
      { status: 500 }
    );
  }
}
